package org.xwlabs.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import org.xwlabs.core.Errors;
import org.xwlabs.core.Validator;

import com.alibaba.fastjson.JSON;

public class SuperMultiActionController extends MultiActionController {
	protected static final Logger logger = LoggerFactory.getLogger(SuperMultiActionController.class);
	
	public final static String REQUEST_FORMAT_NAME = "format";
	public final static String REQUEST_FORMAT_VALUE_JSON = "JSON";
	public final static String REQUEST_FORMAT_VALUE_XML = "XML";

    private Validator validator;
	public Validator getValidator() {
		return validator;
	}
	public void setValidator(Validator validator) {
		this.validator = validator;
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String methodName = this.getMethodNameResolver().getHandlerMethodName(request);
			String format = ServletRequestUtils.getStringParameter(request, REQUEST_FORMAT_NAME, "");
			Errors errors = new Errors();
			ModelAndView modelAndView = new ModelAndView("/information.jsp");
			try{
				//校验数据
				if(validator != null)
					validator.validate(this, methodName, request, errors);
				//执行子类方法
				modelAndView = invokeNamedMethod(methodName, request, response);
			}
			catch(Exception e){
				errors.add(e.getMessage());
			}
			finally{
				if(errors.hasError()){
					modelAndView.getModel().put("errors", errors);
				}
			}
			//处理format json or xml
			if (format.equalsIgnoreCase(REQUEST_FORMAT_VALUE_JSON)) {
				request.setAttribute("json", JSON.toJSONString(modelAndView.getModel()));
				modelAndView.setViewName("/WEB-INF/format/json.jsp");
			}
			if (format.equalsIgnoreCase(REQUEST_FORMAT_VALUE_XML)) {
				modelAndView.setViewName("/WEB-INF/format/xml.jsp");
			}
			return modelAndView;
		} catch (NoSuchRequestHandlingMethodException ex) {
			return handleNoSuchRequestHandlingMethod(ex, request, response);
		}
	}

}
